package top.kaoshanji.s1ch09b;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/4/30 16:41
 */
@Controller
public class MainController {

    private final LoggedUserManagementService loggedUserManagementService;

    // 注入一个会话作用域的bean
    public MainController(LoggedUserManagementService loggedUserManagementService) {
        this.loggedUserManagementService = loggedUserManagementService;
    }

    /**
     * 代码清单-s1ch09b-01：从会话作用域中获取属性
     * @param logout 注销参数
     * @param model Model
     * @return
     */
    @GetMapping("/main")
    public String home(@RequestParam(required = false) String logout, Model model) {

        // 如果注销参数存在，就删除用户名
        if (logout != null) {
            loggedUserManagementService.setUsername(null);
        }

        // 从会话作用域中获取属性
        String userName = loggedUserManagementService.getUsername();

        // 如果已经登录了，那么就不会是null
        if (userName == null) {
            return "redirect:/";
        }

        model.addAttribute("username" , userName);
        return "main.html";

    }



}
